package controller

import (
	"encoding/json"
	"fmt"
	othersmodel "iptv_server/v3/src/models/others_model"
	"iptv_server/v3/src/settings"
	"iptv_server/v3/src/utils"
	"os"
	"path"
	"path/filepath"
	"sort"
	"strings"

	"github.com/gin-gonic/gin"
)

func handleMoreDetail(ctx *gin.Context) {
	// r.GET("/tv/category/:id/:pg/:key", handlecategory)
	// r.GET("/tv/detail/:id/:key", handleDetail) // sourcekey

	reqUrl := ctx.Request.URL.String()

	// fmt.Printf("id: %v\n", id)
	if v, _, ok := cache30min.Get(reqUrl); ok {
		// io.WriteString(ctx.Writer, v)
		ctx.String(200, v)
		return
	}

	// r.GET("/tv/detail_more/:group/:middle/:id", handleMoreDetail)
	group := ctx.Param("group")
	middle := ctx.Param("middle")
	name := ctx.Param("name")

	dir := path.Join(settings.Dir_StaticFile, settings.Dir_Videos, group, middle, name)
	if !utils.IsDir(dir) {
		fmt.Printf("[w] not dir,  dir: %v\n", dir)
		ctx.JSON(200, NotFoundJson)
		return
	}

	vod_play_url, pic := Get_Vod_play_url__and_pic(group, middle, name)
	vod_id := fmt.Sprintf("/tv/detail_more/%s/%s/%s", group, middle, name)
	detail := &othersmodel.ODetail{
		VodId:         vod_id,
		Name:          name,
		Pic:           pic,
		Vod_play_from: "HomeVideo",
		Vod_play_url:  vod_play_url,
	}

	{
		bs, err := json.Marshal(detail)
		if err == nil {
			reqUrl := ctx.Request.URL.String()
			cache30min.Save(reqUrl, string(bs))
			ctx.String(200, string(bs))
		}
	}

}

func Get_Vod_play_url__and_pic(group, middle, dir string) (string, string) {
	// settings.UrlPath_VideoRoot
	d_url := path.Join(settings.UrlPath_VideoRoot, group, middle, dir)
	pic := fmt.Sprintf("%s/__poster.jpg", d_url)

	// 	Dir_StaticFile = "/data/files" //fs
	// 	Dir_Videos     = "videos"

	d_path := path.Join(settings.Dir_StaticFile, settings.Dir_Videos, group, middle, dir)
	vod_txt := path.Join(d_path, "vod.txt")
	if utils.IsExists(vod_txt) {
		if bs, err := os.ReadFile(vod_txt); err == nil {
			vod_play := string(bs)
			vod_play = strings.Trim(vod_play, " #\r\n\t")
			if len(vod_play) > 0 {
				return vod_play, pic
			}
		}
	}
	// d_path := "/tmp/test/"
	videos := make([]string, 0)
	filepath.Walk(d_path, func(p0 string, info os.FileInfo, err error) error {
		if info.IsDir() {
			return nil
		}
		var name string
		if vname, isVideo := utils.GetVideoName(info.Name()); !isVideo {
			return nil
		} else {
			name = vname
		}
		p, _ := strings.CutPrefix(p0, d_path)
		p, _ = strings.CutPrefix(p, "/")

		videos = append(videos, fmt.Sprintf("%s$%s", name, fmt.Sprintf("%s%s", settings.SiteDomain, path.Join(d_url, p))))

		return nil
	})

	// fmt.Printf("Get_Vod_play_url\n")
	sort.Slice(videos, func(i, j int) bool {
		return videos[i] < videos[j]
	})

	// fmt.Printf("Get_Vod_play_url\n")

	return strings.Join(videos, "#"), pic

}
